<?php
class Lib_Form_Validate_DbHasNotRecord extends Zend_Validate_Abstract
{
    /**
     * Error constants
     */
    const ERROR_RECORD_FOUND    = 'recordFound';

    /**
     * Message templates
     * @var array 
     */
    protected $_messageTemplates = array(self::ERROR_RECORD_FOUND    => 'A record matching %value% was found');

    /**
     * Table name
     * @var string
     */
    protected $_table = '';

    /**
     * Field name
     * @var string
     */
    protected $_field = '';

    /**
     * Basic configuration
     *
     * @param string $table
     * @param string $field
     */
    public function __construct($table, $field)
    {
        $this->_table   = (string) $table;
        $this->_field   = (string) $field;
    }

    /**
     * Validation
     *
     * @param string $value
     * @return boolean
     */
    public function isValid($value)
    {
        $em = \Lib\ResLoader::getResource('Doctrine2');
        $field = $this->_field;
        $result = $em->getRepository($this->_table)
                ->findOneBy(array($field=>$value));

        if($result){
            $valid = false;
            $this->_error(self::ERROR_RECORD_FOUND);
        } else {
            $valid = true;
        }
        return $valid;
    }
    
}